package service

import (
	"gitee.com/xiangxiaoc/bodyfat-rate-ranking/mutex/user"
	"log"
	"sort"
	"sync"
)

type BodyFatRateRankingService struct {
	Users     []*user.User
	UsersLock sync.RWMutex
}

func (s *BodyFatRateRankingService) Register(username string) bool {
	u := user.User{
		Username:    username,
		BodyFatRate: 0,
	}
	s.UsersLock.Lock()
	s.Users = append(s.Users, &u)
	s.UsersLock.Unlock()
	log.Printf("[服务端日志] 新增用户 %s\n", u.Username)
	return true
}

func (s *BodyFatRateRankingService) UpdateUserBodyFatRate(username string, rate float64) {
	s.UsersLock.Lock()
	defer s.UsersLock.Unlock()
	for _, u := range s.Users {
		if u.Username == username {
			u.BodyFatRate = rate
			log.Printf("[服务端日志] %s 用户更新了自己的体脂率： %.4f\n", username, rate)
			break
		}
	}
}

func (s *BodyFatRateRankingService) GetRanking(username string) int {
	s.UsersLock.RLock()
	defer s.UsersLock.RUnlock()
	var rateSlice []float64
	for _, u := range s.Users {
		rateSlice = append(rateSlice, u.BodyFatRate)
	}
	sort.Float64s(rateSlice)
	userRate := s.GetBodyFatRate(username)
	return sort.SearchFloat64s(rateSlice, userRate) + 1
}

func (s *BodyFatRateRankingService) GetBodyFatRate(username string) float64 {
	for _, u := range s.Users {
		if u.Username == username {
			return u.BodyFatRate
		}
	}
	return 0
}
